<template>
  <div class="daily-detail">
    <div class="daily-card" v-if="dailyInfo">
      <div class="daily-header">
        <h2>问题详情</h2>
        <el-tag :type="getStateType(dailyInfo.state)">
          {{ getStateText(dailyInfo.state) }}
        </el-tag>
      </div>
      
      <div class="daily-content">
        <div class="info-item">
          <span class="label">提交人：</span>
          <span>{{ dailyInfo.user.realname }}</span>
        </div>
        <div class="info-item">
          <span class="label">提交时间：</span>
          <span>{{ formatDate(dailyInfo.happendTime) }}</span>
        </div>
        <div class="info-item">
          <span class="label">问题描述：</span>
          <div class="rich-content" v-html="dailyInfo.description"></div>
        </div>
        <div class="info-item" v-if="dailyInfo.solution">
          <span class="label">解决方案：</span>
          <div class="rich-content" v-html="dailyInfo.solution"></div>
        </div>
        
        <!-- 修改附件下载区域 -->
        <div class="info-item" v-if="dailyInfo.attachments?.length">
          <span class="label">附件：</span>
          <div class="attachments">
            <span 
              v-for="file in dailyInfo.attachments"
              :key="file.id || file.fileUrl"
              class="attachment"
              @click="handleDownload(file.fileUrl, file.fileName)"
            >
              📎 {{ file.fileName || '附件' }}
            </span>
          </div>
        </div>
        <div class="info-item" v-else-if="dailyInfo.attachment">
          <span class="label">附件：</span>
          <div class="attachments">
            <span 
              class="attachment"
              @click="handleDownload(dailyInfo.attachment, dailyInfo.attachmentName)"
            >
              📎 {{ dailyInfo.attachmentName }}
            </span>
          </div>
        </div>
      </div>
      
      <!-- 如果有关联任务，显示任务信息 -->
      <div class="task-section" v-if="taskInfo">
        <h3>关联任务</h3>
        <div class="task-content">
          <div class="info-item">
            <span class="label">任务标题：</span>
            <span>{{ taskInfo.title }}</span>
          </div>
          <div class="info-item">
            <span class="label">任务状态：</span>
            <el-tag :type="getTaskStateType(taskInfo.state)">
              {{ getTaskStateText(taskInfo.state) }}
            </el-tag>
          </div>
          <div class="info-item">
            <span class="label">负责人：</span>
            <span>{{ taskInfo.responsibleUser.realname ? taskInfo.responsibleUser.realname : "暂未安排" }}</span>
          </div>
          <div class="info-item">
            <span class="label">任务详情：</span>
            <div class="rich-content" v-html="taskInfo.description" @click="handleMediaClick"></div>
          </div>

          <!-- 添加任务状态历史时间轴 -->
          <div class="info-item" v-if="taskInfo.taskStateHistoryList && taskInfo.taskStateHistoryList.length">
            <span class="label">任务的一生：</span>
            <div class="task-history">
              <el-timeline>
                <!-- 起始节点 -->
                <el-timeline-item
                  type="primary"
                  size="large"
                  icon="Pointer"
                  timestamp="开始"
                >
                  <h5>
                    任务创建
                    <template v-if="taskInfo.responsibleUser">
                      <span class="arrow">→</span>
                      <span class="operator">责任人：{{ taskInfo.responsibleUser.realname }}</span>
                    </template>
                  </h5>
                </el-timeline-item>
                
                <!-- 中间状态变更节点 -->
                <el-timeline-item
                  v-for="(history, index) in taskInfo.taskStateHistoryList"
                  :key="index"
                  :type="getStateType(history.state)"
                  :timestamp="history.createdTime"
                >
                  <div class="history-item">
                    <span class="operator">{{ history.user.realname }}操作了任务状态：</span>
                    <span class="arrow">→</span>
                    <span class="state">{{ getStateText(history.state) }}</span>
                    <div class="reason" v-if="history.stateReason" @click="handleMediaClick">
                      原因：<span v-html="processContent(history.stateReason)"></span>
                    </div>
                  </div>
                </el-timeline-item>
                
                <!-- 当前状态节点 -->
                <el-timeline-item
                  :type="getStateType(taskInfo.state)"
                  size="large"
                  :icon="getStateIcon(taskInfo.state)"
                >
                  <h5>当前状态：{{ getStateText(taskInfo.state) }}</h5>
                </el-timeline-item>
              </el-timeline>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加图片预览组件 -->
    <el-image-viewer
      v-if="showViewer"
      :url-list="[currentImage]"
      @close="showViewer = false"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElImageViewer } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import axios from '../plugins/axios'
import { ElDialog, ElImage } from 'element-plus'
import { createApp } from 'vue'
import { h } from 'vue'

const route = useRoute()
const dailyInfo = ref(null)
const taskInfo = ref(null)
const richContent = ref(null)

// 获取日报详情
const fetchDailyDetail = async () => {
  try {
    const response = await axios.get(`/daily/${route.params.id}`)
    if (response.data.code === 1) {
      dailyInfo.value = response.data.data
      // 如果日报已转为任务，获取任务信息
      if (dailyInfo.value.task === 1) {
        fetchTaskInfo()
      }
    } else {
      ElMessage.error('获取日报详情失败')
    }
  } catch (error) {
    console.error('获取日报详情失败:', error)
    ElMessage.error('获取日报详情失败')
  }
}

// 获取任务信息
const fetchTaskInfo = async () => {
  try {
    const response = await axios.get(`/task/${route.params.id}`)
    if (response.data.code === 1) {
      taskInfo.value = response.data.data
    }
  } catch (error) {
    console.error('获取任务信息失败:', error)
  }
}

// 状态相关函数
const getStateType = (state) => {
  const stateMap = {
    1: 'warning',   // 未解决
    2: 'primary',   // 处理中
    3: 'success',   // 已解决
    4: 'info'       // 已关闭
  }
  return stateMap[state] || 'info'
}

const getStateText = (state) => {
  const stateMap = {
    1: '未解决',
    2: '处理中',
    3: '已解决',
    4: '已关闭'
  }
  return stateMap[state] || '未知状态'
}

const getTaskStateType = (state) => {
  const stateMap = {
    1: 'warning',   // 待处理
    2: 'primary',   // 进行中
    3: 'success',   // 已完成
    4: 'info'       // 已关闭
  }
  return stateMap[state] || 'info'
}

const getTaskStateText = (state) => {
  const stateMap = {
    1: '待处理',
    2: '进行中',
    3: '已完成',
    4: '已关闭'
  }
  return stateMap[state] || '未知状态'
}

// 获取状态图标
const getStateIcon = (state) => {
  switch (state) {
    case 2: return 'Loading'    // 进行中
    case 3: return 'Select'     // 已完成
    case 4: return 'CircleClose' // 已关闭
    default: return 'More'      // 其他状态
  }
}

// 处理内容中的链接
const processContent = (content) => {
  if (!content) return ''
  
  const div = document.createElement('div')
  div.innerHTML = content
  
  // 处理所有链接
  const links = div.getElementsByTagName('a')
  for (let link of links) {
    link.setAttribute('target', '_blank')
    link.setAttribute('rel', 'noopener noreferrer')
  }
  
  return div.innerHTML
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  
  // 格式化年月日
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  
  // 格式化时分秒
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  
  // 返回格式化后的字符串
  return `${year}.${month}.${day} ${hours}:${minutes}:${seconds}`
}

// 图片预览相关
const showViewer = ref(false)
const currentImage = ref('')

// 处理媒体元素的交互
const handleMediaElements = () => {
  if (!richContent.value) return

  // 处理图片
  const images = richContent.value.getElementsByTagName('img')
  images.forEach(img => {
    img.style.cursor = 'pointer'
    img.onclick = () => {
      currentImage.value = img.src
      showViewer.value = true
    }
  })

  // 处理视频
  const videos = richContent.value.getElementsByTagName('video')
  videos.forEach(video => {
    // 确保视频有控制条
    video.controls = true
    // 添加点击全屏功能
    video.onclick = () => {
      if (video.requestFullscreen) {
        video.requestFullscreen()
      } else if (video.webkitRequestFullscreen) {
        video.webkitRequestFullscreen()
      } else if (video.msRequestFullscreen) {
        video.msRequestFullscreen()
      }
    }
  })
}

// 监听内容变化
watch(() => taskInfo.description, () => {
  nextTick(() => {
    handleMediaElements()
  })
})

// 组件挂载时初始化
onMounted(() => {
  fetchDailyDetail()
  handleMediaElements()
})

// 修改下载处理函数
const handleDownload = (url, fileName) => {
  const link = document.createElement('a')
  link.href = url
  link.download = fileName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const handleMediaClick = (event) => {
  const target = event.target
  
  // 处理图片点击
  if (target.tagName === 'IMG') {
    const imageList = [target.src]
    
    // 创建图片预览组件
    const div = document.createElement('div')
    document.body.appendChild(div)
    
    // 创建预览组件实例
    const app = createApp({
      render() {
        return h(ElImageViewer, {
          urlList: imageList,
          onClose: () => {
            app.unmount()
            div.remove()
          }
        })
      }
    })
    
    app.mount(div)
  }
  
  // 处理视频点击
  if (target.tagName === 'VIDEO') {
    if (target.requestFullscreen) {
      target.requestFullscreen()
    } else if (target.webkitRequestFullscreen) {
      target.webkitRequestFullscreen()
    }
  }
}
</script>

<style scoped>
.daily-detail {
  padding: 20px;
}

.daily-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.daily-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.daily-header h2 {
  margin: 0;
  color: #303133;
}

.info-item {
  margin-bottom: 15px;
}

.label {
  color: #606266;
  margin-right: 8px;
  font-weight: 500;
}

.description {
  margin: 10px 0;
  white-space: pre-wrap;
  line-height: 1.6;
}

.task-section {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.task-section h3 {
  color: #303133;
  margin-bottom: 15px;
}

.task-content {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.rich-content {
  margin: 10px 0;
  line-height: 1.6;
}

.rich-content :deep(img) {
  max-width: 100%;
  height: auto;
  cursor: zoom-in;
}

.rich-content :deep(video) {
  max-width: 100%;
  height: auto;
  cursor: pointer;
}

/* 视频控制条样式优化 */
.rich-content :deep(video::-webkit-media-controls) {
  background-color: rgba(0, 0, 0, 0.5);
}

.rich-content :deep(video::-webkit-media-controls-panel) {
  display: flex;
  align-items: center;
  padding: 4px;
}

.rich-content :deep(p) {
  margin: 8px 0;
}

/* 确保弹出的图片查看器在最上层 */
:deep(.el-image-viewer__wrapper) {
  z-index: 2100;
}

/* 添加过渡动画 */
.rich-content :deep(img),
.rich-content :deep(video) {
  transition: all 0.3s ease;
}

/* 媒体查询，适配移动端 */
@media screen and (max-width: 768px) {
  .rich-content :deep(img),
  .rich-content :deep(video) {
    width: 100%;
  }
}

.attachments {
  margin-top: 8px;
}

.attachment {
  color: #409EFF;
  cursor: pointer;
  margin-right: 10px;
}

.attachment:hover {
  color: #66b1ff;
}

.task-history {
  margin-top: 12px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.history-item {
  padding: 8px 0;
}

.history-item .operator {
  font-weight: 500;
  color: #409EFF;
}

.history-item .arrow {
  margin: 0 8px;
  color: #909399;
}

.history-item .state {
  font-weight: 500;
}

.history-item .reason {
  margin-top: 8px;
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
}

.history-item .reason :deep(a) {
  color: #409EFF;
  text-decoration: none;
}

.history-item .reason :deep(a:hover) {
  color: #66b1ff;
  text-decoration: underline;
}

.history-item .reason :deep(img) {
  max-width: 100%;
  height: auto;
  cursor: pointer;
  margin: 8px 0;
}

.history-item .reason :deep(video) {
  max-width: 100%;
  height: auto;
  margin: 8px 0;
}

:deep(.el-timeline-item__node--large) {
  width: 16px;
  height: 16px;
}

:deep(.el-timeline-item__timestamp) {
  color: #909399;
  font-size: 13px;
}
</style> 
